package com.diorsunion.hedge.algo;

import com.diorsunion.hedge.domain.AccountManager;
import com.diorsunion.hedge.dal.entity.stock.StockPrice;
import com.diorsunion.hedge.dal.entity.TradeLog;
import com.diorsunion.hedge.util.CalendarUtils;
import com.diorsunion.hedge.domain.MACD;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.diorsunion.hedge.util.CurrencyUtils.*;

/**
 * MACD
 * 金叉买，死叉卖
 * Created by wanglaoshi on 2016/4/16.
 */
public class Oper11 extends Operation {

    public Oper11(Map<String, Integer> params) {
        super(params);
    }

    private static final Set<MACD> buy_set = Sets.newHashSet(new MACD(MACD.Type.JINCHA, 3));
    private static final Set<MACD> sell_set = Sets.newHashSet(new MACD(MACD.Type.SICHA, 3));

    private StockPrice.PriceType priceType = StockPrice.PriceType.CLOSE;//用收盘价来计算
    private AccountManager account_period_begin = null;//周期记录日的账户情况,静态止损

    @Override
    public void oper(AccountManager accountManager, List<AccountManager> account_per_days) {

        if(account_per_days.size()==1){
            account_period_begin = accountManager;
        }
        if (account_per_days.size() < 3) {
            return;
        }
        AccountManager account_yes = account_per_days.get(account_per_days.size()-2);
        accountManager.stockPool.forEach((stock, num) -> {
            StockPrice stockPrice = stock.getStockPrice(accountManager.date);
            //用昨天的MACD作为买卖标准
            StockPrice stockPrice_yes = stock.getStockPrice(account_yes.date);
            if (stockPrice_yes == null) {
                return;
            }
            int trade_num = 0;
            for(MACD macd :stockPrice.macds){
                if(buy_set.contains(macd)){
                    trade_num = (int) (accountManager.getTotalValue(priceType) / stockPrice.open / 3);
                    System.out.println(stock.code + ":" + CalendarUtils.formatSimple(accountManager.date) +  macd +  ",收盘价:" + format(stockPrice.close) + ",开仓多单");
                    break;
                }else if(sell_set.contains(macd)){
                    trade_num = - (int) (accountManager.getTotalValue(priceType) / stockPrice.open / 3);
                    System.out.println(stock.code + ":" + CalendarUtils.formatSimple(accountManager.date) +  macd +  ",收盘价:" + format(stockPrice.close) + ",开仓空单");
                    break;
                }
            }
            if(trade_num!=0){
                TradeLog tradeLog = accountManager.trade(stock, trade_num, priceType);
                account_period_begin = accountManager;
                if (tradeLog != null) {
                    tradeLogs.add(tradeLog);
                }
            }
        });
    }

    @Override
    public String getDesc() {
        return "MACD买卖法";
    }
}
